/* eslint-disable no-shadow */
/* eslint-disable react/destructuring-assignment */
/* eslint-disable import/no-extraneous-dependencies */
// /* eslint-disable no-underscore-dangle */
// /* eslint-disable import/no-extraneous-dependencies */
// /* eslint-disable import/no-duplicates */
// /* eslint-disable no-unused-vars */
// /* eslint-disable react/sort-comp */
// /* eslint-disable react/destructuring-assignment */
// /* eslint-disable react/no-access-state-in-setstate */
// /* eslint-disable react/no-unused-state */
import React from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Col, Button, Progress, Select, message } from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BatchUpload from '../../components/BatchUpload/Index';
import UpdateInfoFinish from './UpdateInfoFinish';
import downloadFile from '@/utils/utils';
import getSys from './judgeSys';

const { Option } = Select;
const FormItem = Form.Item;
@Form.create()
@connect(({ annualbasic, publicdata, login }) => ({
  batchQuery: annualbasic.batchQuery,
  declarationData: annualbasic.declarationData,
  fileId: publicdata.downloadFile.fileId,
  fileName: publicdata.downloadFile.fileName,
  updateYmOpts: annualbasic.updateYmOpts,
  updatePercent: annualbasic.updatePercent,
  login,
}))
@Form.create({})
class Batch extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      interval: () => {},
      updateLoading: false,
      currentStep: 0,
      showProgress: false,
      resultInfo: {
        // 结果数据必传
        collectEmpNumOld: 0, // 原采集数据
        collectEmpNumNew: 0, // 新采集数据
        collectAddEmpNum: 0, // 增员数据
        collectDeduEmpNum: 0, // 减员人数
      },
    };
  }

  componentDidMount() {
    const { dispatch, location, login } = this.props;
    const { yearAdjTskId } = queryString.parse(location.search);
    const { systemList, baseUser } = login;
    const userType = getSys(systemList, baseUser, location);
    this.setState({
      yearAdjTskId,
    });
    dispatch({
      type: 'annualbasic/fetchDetails',
      payload: {
        yearAdjTskId,
        userType,
      },
    }).then(res => {
      if (res.success) {
        const start = res.data && moment(res.data.adjYm).format('YYYY-MM');
        const end = res.data && moment(res.data.validYm).format('YYYY-MM');
        dispatch({
          type: 'annualbasic/handleUpdateYmOpts',
          payload: [start, end],
        });
      }
    });
  }

  componentWillUnmount = () => {
    const { interval } = this.state;
    clearInterval(interval);
  };

  // 设置当前位置
  setCurrentstep = currentStep => {
    this.setState({ currentStep });
  };

  // 关闭
  closeProgress = () => {
    router.go(-1);
  };

  // 更新
  onNext = () => {
    const { dispatch, form } = this.props;
    const { yearAdjTskId } = this.state;
    form.validateFields(['adjUpdtYm'], (err, values) => {
      if (err) return;
      dispatch({
        type: 'annualbasic/updateInfoProgress',
        payload: {
          yearAdjTskId,
          ...values,
        },
      }).then(res => {
        if (res.success) {
          this.setState({
            showProgress: true,
            updateLoading: true,
          });
          dispatch({
            type: 'annualbasic/getProgress',
            payload: {
              yearAdjTskId,
              ...values,
            },
          }).then(res => {
            // 初始化如果没有完成
            if (res === 100) {
              const { currentStep, interval } = this.state;
              this.setState({
                updateLoading: false,
              });
              this.setCurrentstep(currentStep + 1);
              clearInterval(interval);
            } else {
              clearInterval(this.state.interval);
              this.setState({
                interval: setInterval(() => {
                  const { updatePercent } = this.props;
                  const { currentStep, interval } = this.state;
                  if (updatePercent === 100) {
                    this.setState({
                      updateLoading: false,
                    });
                    this.setCurrentstep(currentStep + 1);
                    clearInterval(interval);
                  }
                  dispatch({
                    type: 'annualbasic/getProgress',
                    payload: {
                      yearAdjTskId,
                      ...values,
                    },
                  });
                }, 300000),
              });
            }
          });
        } else {
          clearInterval(this.state.interval);
          message.warning(res.message || '服务端错误');
        }
      });
    });
  };

  // 下载增员数据
  downLoadIncrease = () => {
    const { yearAdjTskId } = this.state;
    downloadFile({ yearAdjTskId }, '/osApi/annualAdj/custCollectAddEmpByOs/downFile', 'POST');
  };

  // 关闭返回
  closeUpdate = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'annualbasic/updateModelData',
      payload: {
        updatePercent: 0,
      },
    });
    router.go(-1);
  };

  render() {
    const {
      declarationData,
      updateYmOpts,
      updatePercent,
      form: { getFieldDecorator },
    } = this.props;
    const { currentStep, resultInfo, showProgress, updateLoading } = this.state;
    const formItemLayout1 = {
      labelCol: {
        xxl: {
          span: 8,
        },
        xl: {
          span: 8,
        },
      },
      wrapperCol: {
        xxl: {
          span: 16,
        },
        xl: {
          span: 16,
        },
      },
    };
    return (
      <PageHeaderWrapper>
        <BatchUpload currentStep={currentStep}>
          <div
            style={{ margin: '0 auto', marginTop: 50 }}
            title="更新数据"
            currentStep={currentStep}
            setCurrentstep={this.setCurrentstep}
          >
            <Form {...formItemLayout1}>
              <Col md={17} offset={4}>
                <FormItem label={<span>采集人员年月</span>}>
                  <span style={{ height: 32, lineHeight: '32px', display: 'inline-block' }}>
                    {moment(declarationData.adjYm).format('YYYY-MM') || '--'}
                  </span>
                </FormItem>
              </Col>
              <Col md={17} offset={4}>
                <FormItem label={<span>开始生效年月</span>}>
                  <span style={{ height: 32, lineHeight: '32px', display: 'inline-block' }}>
                    {moment(declarationData.validYm).format('YYYY-MM') || '--'}
                  </span>
                </FormItem>
              </Col>
              <Col md={17} offset={4}>
                <FormItem label={<span>更新采集人员年月</span>}>
                  {getFieldDecorator('adjUpdtYm', {
                    rules: [{ required: true, message: '请选择更新采集人员年月' }],
                  })(
                    <Select
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      placeholder="请选择"
                      style={{ width: '60%', maxWidth: 320 }}
                    >
                      {updateYmOpts.map(item => (
                        <Option key={item.value}>{item.label}</Option>
                      ))}
                    </Select>
                  )}
                </FormItem>
              </Col>
            </Form>
            {/* <Col md={10} style={{ textAlign: 'right' }}>
              采集人员年月：
            </Col>
            <Col md={14}>{moment(declarationData.adjYm).format('YYYY-MM') || '--'}</Col>
            <Col md={10} style={{ textAlign: 'right' }}>
              开始生效年月：
            </Col>
            <Col md={14}>{moment(declarationData.validYm).format('YYYY-MM') || '--'}</Col> */}

            <Col offset={10} md={14} style={{ color: 'red' }}>
              注：采集人员不能重复更新，请您确认后更新。
            </Col>
            <Col md={10} offset={10} style={{ color: 'red' }}>
              如果当前地区不需要更新最新的采集人员数据，请关闭。
            </Col>
            <Col
              xxl={{ span: 10, offset: 6 }}
              xl={{ span: 10, offset: 7 }}
              style={{ textAlign: 'right', marginTop: 30 }}
            >
              {showProgress ? <Progress percent={updatePercent} style={{ maxWidth: 570 }} /> : null}
            </Col>
            <Col md={24} sm={24} style={{ textAlign: 'center', marginTop: 100 }}>
              <Button style={{ marginRight: 8 }} onClick={() => this.closeProgress()}>
                关闭
              </Button>
              <Button type="primary" loading={updateLoading} onClick={() => this.onNext()}>
                更新
              </Button>
            </Col>
          </div>

          <UpdateInfoFinish
            title="下载增员数据"
            resultInfo={resultInfo}
            downLoadIncrease={this.downLoadIncrease}
            closeUpdate={this.closeUpdate}
          />
        </BatchUpload>
      </PageHeaderWrapper>
    );
  }
}

export default Batch;
